# coding=utf-8
import functools

import datetime
from django.core.exceptions import ObjectDoesNotExist

from recite.models import UserLogger


def with_recite_logger(request):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            cur = datetime.datetime.now()
            date_today = datetime.date(cur.year, cur.month, cur.day)
            try:
                log_data = UserLogger.get_log_data(request.user, date_today)
            except Exception:
                log_data = UserLogger()
                log_data.user = request.user.id
                log_data.date = date_today

            # 记录session中的current_id以及review_list
            log_data.current = request.session.get('current_id', 0)
            log_data.review = request.session.get('review_list', [])
            log_data.save()
            return func(*args, **kwargs)
        return wrapper
    return decorator


def recite_logger(request):
    cur = datetime.datetime.now()
    date_today = datetime.date(cur.year, cur.month, cur.day)
    try:
        log_data = UserLogger.get_log_data(request.user, date_today)
    except ObjectDoesNotExist:
        log_data = UserLogger()
        log_data.user = request.user
        log_data.date = date_today

    # 记录session中的current_id以及review_list
    log_data.current = request.session.get('current_id', 0)
    log_data.review = request.session.get('review_list', {})
    log_data.save()
